package top.hepingan.java.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import top.hepingan.java.common.Result;
import top.hepingan.java.entity.Shop;
import top.hepingan.java.entity.ShopImage;
import top.hepingan.java.entity.ShopStar;
import top.hepingan.java.entity.User;
import top.hepingan.java.mapper.ShopImageMapper;
import top.hepingan.java.mapper.ShopMapper;
import top.hepingan.java.mapper.ShopStarMapper;
import top.hepingan.java.mapper.UserMapper;
import top.hepingan.java.service.ShopService;
import top.hepingan.java.utils.AliUploadUtils;
import top.hepingan.java.utils.BeanUtils;
import top.hepingan.java.utils.UserUtils;
import top.hepingan.java.vo.ForumVo;
import top.hepingan.java.vo.ShopVo;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

@RequiredArgsConstructor
@RequestMapping("/shop")
@RestController
@Slf4j
public class ShopController {

    private final ShopService shopService;
    private final ShopImageMapper shopImageMapper;
    private final UserMapper userMapper;
    private final ShopStarMapper shopStarMapper;
    private final ShopMapper shopMapper;
    private final AliUploadUtils aliUploadUtils;

    /**
     * 根据标题分页查询帖子
     * @param pageNum
     * @param shopName
     * @return
     */
    @GetMapping("/list")
    public Result list(@RequestParam Integer pageNum, @RequestParam String shopName,@RequestParam String category) {
        List<ShopVo> forumList = shopService.pageBynum(pageNum,shopName,null,category,false,true);
        return Result.data(forumList);
    }

    /**
     * 发布商品
     * @param shopVo
     * @return
     */
    @PostMapping("/publish")
    public Result publish(@RequestBody ShopVo shopVo) {
        shopService.publish(shopVo);
        return Result.ok();
    }

    /**
     * 根据id获取商品详情
     * @param id
     * @return
     */
    @GetMapping("/getById")
    public Result getById(@RequestParam Long id) {
        ShopVo shopVo = getShopVo(id);
        return Result.data(shopVo);
    }

    /**
     * 根据id获取商品详情
     * @param id
     * @return
     */
    private ShopVo getShopVo(Long id) {
        Shop shop = shopService.getById(id);
        ShopVo shopVo = BeanUtils.copyClassProperTies(shop, ShopVo.class);
        List<ShopImage> shopImages = shopImageMapper.selectList(new QueryWrapper<ShopImage>().lambda()
                .eq(ShopImage::getShopId, id));
        List<String> imageList = new ArrayList<>();
        for (ShopImage shopImage : shopImages) {
            imageList.add(shopImage.getImageUrl());
        }
        shopVo.setImageUrl(imageList);
        User user = userMapper.selectOne(new QueryWrapper<User>().lambda().eq(User::getId, shop.getUserId()));
        shopVo.setUsername(user.getUsername());
        shopVo.setLevel(user.getLevel());
        shopVo.setAvatar(user.getAvatar());
        ShopStar shopStar = shopStarMapper.selectOne(new QueryWrapper<ShopStar>().lambda()
                .eq(ShopStar::getShopId, id)
                .eq(ShopStar::getUserId, UserUtils.getCurrentLoginId()));
        shopVo.setIsFavorite(shopStar != null);
        shopVo.setAvatarFrameUrl(user.getAvatarFrameUrl());
        return shopVo;
    }

    /**
     * 获取收藏的商品
     * @return
     */
    @GetMapping("/myFavorite")
    public Result myFavorite(@RequestParam Integer pageNum) {
        Page<ShopStar> page = new Page<>(pageNum, 10);
        List<ShopStar> shopStars = shopStarMapper.selectPage(page,new QueryWrapper<ShopStar>().lambda()
                .eq(ShopStar::getUserId, UserUtils.getCurrentLoginId())).getRecords();
        List<ShopVo> shopVoList = new ArrayList<>();
        for (ShopStar shopStar : shopStars){
            shopVoList.add(getShopVo(shopStar.getShopId()));
        }
        return Result.data(shopVoList);
    }

    /**
     * 收藏或取消收藏商品
     * @param id
     * @return
     */
    @GetMapping("/toggleFavorite")
    public Result toggleFavorite(@RequestParam Long id) {
        ShopStar shopStar = shopStarMapper.selectOne(new QueryWrapper<ShopStar>().lambda()
                .eq(ShopStar::getShopId, id)
                .eq(ShopStar::getUserId, UserUtils.getCurrentLoginId()));
        if (shopStar != null) {
            shopStarMapper.deleteById(shopStar);
        } else {
            shopStar = new ShopStar();
            shopStar.setShopId(id);
            shopStar.setUserId(UserUtils.getCurrentLoginId());
            shopStarMapper.insert(shopStar);
        }
        return Result.ok();
    }

    /**
     * 获取我的商品
     * @param pageNum
     * @return
     */
    @GetMapping("/myShop")
    public Result myShop(@RequestParam Integer pageNum) {
        Page<Shop> page = new Page<>(pageNum, 10);
        List<Shop> shopList = shopMapper.selectPage(page,new QueryWrapper<Shop>().lambda()
                .orderByDesc(Shop::getCreatedTime)
                .eq(Shop::getUserId, UserUtils.getCurrentLoginId())).getRecords();
        List<ShopVo> shopVoList = new ArrayList<>();
        for (Shop shop : shopList){
            shopVoList.add(getShopVo(shop.getId()));
        }
        return Result.data(shopVoList);
    }

    /**
     * 根据userid获取用户商品
     * @param pageNum
     * @return
     */
    @GetMapping("/getShopByUserId")
    public Result getShopById(@RequestParam Integer pageNum,@RequestParam Long userId) {
        Page<Shop> page = new Page<>(pageNum, 10);
        List<Shop> shopList = shopMapper.selectPage(page,new QueryWrapper<Shop>().lambda()
                .eq(Shop::getStatus, 1)
                .orderByDesc(Shop::getCreatedTime)
                .eq(Shop::getUserId, userId)).getRecords();
        List<ShopVo> shopVoList = new ArrayList<>();
        for (Shop shop : shopList){
            shopVoList.add(getShopVo(shop.getId()));
        }
        return Result.data(shopVoList);
    }

    /**
     * 设置商品上下架
     * @param id
     * @return
     */
    @GetMapping("/setOnline")
    public Result setOnline(@RequestParam Long id) {
        Shop shop = shopMapper.selectOne(new QueryWrapper<Shop>().lambda()
                .eq(Shop::getId, id));
        if (!Objects.equals(shop.getUserId(), UserUtils.getCurrentLoginId())){
            return Result.error("这不是您的商品，您没有权限");
        }
        if (shop.getIsOnline()){
            shop.setIsOnline(false);
        }else shop.setIsOnline(true);
        shopMapper.updateById(shop);
        return Result.ok();
    }

    /**
     * 修改商品
     * @param shopVo
     * @return
     */
    @PostMapping("/update")
    public Result update(@RequestBody ShopVo shopVo) {
        Shop shop = BeanUtils.copyClassProperTies(shopVo, Shop.class);
        shop.setStatus(0);
        for (String url : shopVo.getImageUrl()){
            ShopImage shopImage = new ShopImage();
            shopImage.setShopId(shop.getId());
            shopImage.setImageUrl(url);
            shopImageMapper.insert(shopImage);
        }
        shopService.updateById(shop);
        return Result.ok();
    }

    /**
     * 删除图片
     * @param imgUrl
     * @return
     */
    @PostMapping("/deleteImg")
    public Result deleteImg(@RequestBody String imgUrl) {
        ShopImage shopImage = shopImageMapper.selectOne(new QueryWrapper<ShopImage>().lambda()
                .eq(ShopImage::getImageUrl, imgUrl));
        shopImageMapper.deleteById(shopImage);
        aliUploadUtils.deleteFile(imgUrl);
        return Result.ok();
    }

}
